# --*-- coding:utf-8 --*--
# @Time: 2025/6/1 22:14
# @Author: Mark
# @Email: 17521559996@163.com
# @File: purchase_order_wizard.py
# @Software : PyCharm

from odoo import models, fields, api
from odoo.exceptions import UserError


class PurchaseOrderWizard(models.TransientModel):
    _name = 'purchase.order.wizard'
    _description = '申请创建采购单'

    partner_id = fields.Many2one('res.partner', string='供应商', domain=[('supplier_rank', '>', 0)], required=True)
    sale_order_id = fields.Many2one('sale.order', string='销售订单')
    order_line_ids = fields.One2many('purchase.order.wizard.line', 'wizard_id', string='采购明细')

    def action_create_purchase_order(self):
        if not self.order_line_ids:
            raise UserError("请添加至少一条采购明细。")
        po = self.env['purchase.order'].create({
            'partner_id': self.partner_id.id,
            'origin': self.sale_order_id.name,
            'customer_reference': self.sale_order_id.customer_reference,
            'order_line': [
                (0, 0, {
                    'product_id': line.product_id.id,
                    'name': line.product_id.name,
                    'product_qty': line.product_qty,
                    'price_unit': line.price_unit,
                    'date_planned': fields.Date.today(),
                    'sale_line_id': line.sale_line_id.id

                })
                for line in self.order_line_ids
            ]
        })

        return {
            'type': 'ir.actions.act_window',
            'res_model': 'purchase.order',
            'view_mode': 'form',
            'res_id': po.id,
            'target': 'current',
        }


class PurchaseOrderWizardLine(models.TransientModel):
    _name = 'purchase.order.wizard.line'
    _description = '采购单明细'

    sale_line_id = fields.Many2one('sale.order.line', string='销售订单行')
    wizard_id = fields.Many2one('purchase.order.wizard', string='向导')
    product_id = fields.Many2one('product.product', string='产品', required=True)
    product_qty = fields.Float(string='数量', required=True, default=1.0)
    price_unit = fields.Float(string='单价', required=True)

    @api.onchange('sale_line_id')
    def _onchange_sale_line_id(self):
        for rec in self:
            if rec.sale_line_id:
                rec.product_id = rec.sale_line_id.product_id
                rec.product_qty = rec.sale_line_id.purchase_qty_to_order  # 用刚才的计算字段
                rec.price_unit = rec.sale_line_id.purchase_price
